package com.smarth.zhizulian.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.smarth.zhizulian.R;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.app.EventActivity;
import com.smarth.zhizulian.bean.BaseEntity;
import com.smarth.zhizulian.bean.task.TaskUserTasks;
import com.smarth.zhizulian.bean.user.DiscipleIndex;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.entity.Mission;
import com.smarth.zhizulian.entity.UserInfo;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.observer.ProgressObserver;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.popupwindow.CoinDialog;
import com.smarth.zhizulian.popupwindow.HongBaoDialog;
import com.smarth.zhizulian.popupwindow.NewHongBaoDialog;
import com.smarth.zhizulian.popupwindow.SignDialog;
import com.smarth.zhizulian.utils.KumaToast;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.adapter.PageDataAdapter;
import com.smarth.zhizulian.utils.listhelper.impl.model.HttpPageDataModel;
import com.smarth.zhizulian.view.ExpandableLayout;
import com.smarth.zhizulian.view.LoadingLayout;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 18865 on 2017/12/26.
 */

public class MissionActivity extends EventActivity {
    @BindView(R.id.el_new_1)
    ExpandableLayout elNew1;
    @BindView(R.id.el_new_2)
    ExpandableLayout elNew2;
    @BindView(R.id.el_new_3)
    ExpandableLayout elNew3;
    @BindView(R.id.el_everyday_1)
    ExpandableLayout elEveryday1;
    @BindView(R.id.el_everyday_2)
    ExpandableLayout elEveryday2;
    @BindView(R.id.el_everyday_5)
    ExpandableLayout elEveryday5;
    @BindView(R.id.el_everyday_3)
    ExpandableLayout elEveryday3;
    @BindView(R.id.el_everyday_4)
    ExpandableLayout elEveryday4;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.ll_new)
    LinearLayout llNew;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.iv_day1)
    ImageView ivDay1;
    @BindView(R.id.iv_day2)
    ImageView ivDay2;
    @BindView(R.id.iv_day3)
    ImageView ivDay3;
    @BindView(R.id.iv_day4)
    ImageView ivDay4;
    @BindView(R.id.iv_day5)
    ImageView ivDay5;
    @BindView(R.id.iv_day6)
    ImageView ivDay6;
    @BindView(R.id.iv_day7)
    ImageView ivDay7;
    @BindView(R.id.btn_sign)
    Button btnSign;
    @BindView(R.id.tv_luckmoney_hint)
    TextView tvLuckmoneyHint;
    @BindView(R.id.iv_luckmoney)
    ImageView ivLuckmoney;
    private List<ExpandableLayout> elList;
    private String[] headerArray = new String[]{"首次分享阅读至朋友圈", "首次分享阅读至微信群", "首次收徒", "分享普通文章", "分享高价文章", "晒晒收入", "幸运红包", "阅读奖励"};
    private String[] descArray = new String[]{"首次分享文章/视频至朋友圈即可获得奖励"
            , "首次分享文章/视频至微信群即可获得奖励"
            , "首次成功邀请一名徒弟，徒弟转发文章并被有效阅读，您将会获得奖励"
            , "分享文章到微信朋友圈、微信群，被好友仔细阅读后，即可获得60~100金币／次好友阅读奖励，奖励无上限！（具体奖励金额以标注的价格为准）"
            , "分享标注为“高价”的内容到朋友圈、微信群，被好友有效阅读后，即可获得100~240金币／次好友阅读奖励，奖励无上限（具体奖励金额以标注价格为准）"
            , "每天首次分享“收入海报”到朋友圈当好友看到后才能领到奖励"
            , "每天24小时内完成前面三项日常任务后可以领取一个幸运红包，金额最高3000金币（金额随机）"
            , "每天有效阅读文章/视频，最高每天可获得20次阅读奖励。"
    };
    private int[] coinArray = new int[]{R.drawable.mission_coin_100
            , R.drawable.mission_coin_100
            , R.drawable.mission_coin_1000
            , R.drawable.mission_coin_60_100
            , R.drawable.mission_coin_100_240
            , R.drawable.mission_coin_30
            , R.drawable.mission_coin_3000
            , R.drawable.mission_coin_5_100
    };
    private RefreshHelper<TaskUserTasks> refreshHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mission);
        ButterKnife.bind(this);
        setTitlebar("任务大厅", true);
        init();
    }

    private void init() {
        refreshHelper = new RefreshHelper<>(mContext, llLoadinglayout, null);
        refreshHelper.setDataModel(new HttpPageDataModel<TaskUserTasks>(mContext) {
            @Override
            public Observable<TaskUserTasks> getObservable() {
                return KumaHttp.getService().taskUserTasks()
                        .compose(RxCompos.<TaskUserTasks>getBELoginCompos());
            }
        });
        refreshHelper.setDataAdapter(new PageDataAdapter<TaskUserTasks>() {
            @Override
            public void onGetData(TaskUserTasks taskUserTasks, boolean isRefresh) {
                super.onGetData(taskUserTasks, isRefresh);
                handleData(taskUserTasks);
            }
        });
        refreshHelper.refresh();
    }

    private void initMission(TaskUserTasks tut) {
        elList = new ArrayList<>();
        elList.add(elNew1);
        elList.add(elNew2);
        elList.add(elNew3);
        elList.add(elEveryday1);
        elList.add(elEveryday2);
        elList.add(elEveryday3);
        elList.add(elEveryday4);
        elList.add(elEveryday5);

        for (int i = 0; i < elList.size(); i++) {
            ExpandableLayout el = elList.get(i);
            View headerView = el.getHeaderRelativeLayout();
            TextView tv_header = headerView.findViewById(R.id.tv_header);
            ImageView iv_coin = headerView.findViewById(R.id.iv_coin);
            Button btn_share = headerView.findViewById(R.id.btn_share);

            tv_header.setText(headerArray[i]);
            iv_coin.setImageResource(coinArray[i]);

            View footerView = el.getContentRelativeLayout();
            TextView tv_desc = footerView.findViewById(R.id.tv_desc);
            tv_desc.setText(descArray[i]);

            switch (i) {
                case 0:
                    setBtnEnable(btn_share, tut.getNoviceShareCircle() == 0 ? true : false);
                    btn_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MainActivity.openClearTask(mContext, MainActivity.MODE_NORMAL);
                        }
                    });
                    break;
                case 1:
                    setBtnEnable(btn_share, tut.getNoviceShare() == 0 ? true : false);
                    btn_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MainActivity.openClearTask(mContext, MainActivity.MODE_NORMAL);
                        }
                    });
                    break;
                case 2:
                    setBtnEnable(btn_share, tut.getNoviceDisciple() == 0 ? true : false);
                    btn_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MainActivity.openClearTask(mContext, MainActivity.MODE_DISCIPLE);
                        }
                    });
                    break;
                case 3:
                    setBtnEnable(btn_share, tut.getEveryShareCommon() == 0 ? true : false);
                    btn_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MainActivity.openClearTask(mContext, MainActivity.MODE_NORMAL);
                        }
                    });
                    break;
                case 4:
                    setBtnEnable(btn_share, tut.getEveryShareHigh() == 0 ? true : false);
                    btn_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MainActivity.openClearTask(mContext, MainActivity.MODE_HIGH);
                        }
                    });
                    break;
                case 5:
                    setBtnEnable(btn_share, tut.getEveryShowMoney() == 0 ? true : false);
                    btn_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            KumaHttp.getService().discipleIndex()
                                    .compose(RxCompos.<DiscipleIndex>getBELoginCompos())
                                    .subscribe(new ProgressObserver<DiscipleIndex>(mContext) {
                                        @Override
                                        public void onNext(@NonNull DiscipleIndex mDiscipleIndex) {
                                            UserInfo ui = new UserInfo();
                                            ui.setAvatar(mDiscipleIndex.getAcatar());
                                            ui.setCoin(mDiscipleIndex.getCoin());
                                            ui.setName(mDiscipleIndex.getNickname());
                                            ui.setQrcode(mDiscipleIndex.getQrCodeImageUrl());
                                            ui.setWechatUrl(mDiscipleIndex.getWxShareUrl());
                                            ShareMeActivity.openForMission(mContext, ui);
                                        }
                                    });
                        }
                    });
                    break;
                case 6:
                    if (tut.getEveryShareCommon() == 1 && tut.getEveryShareHigh() == 1 && tut.getEveryShowMoney() == 1) {
                        btn_share.setEnabled(tut.getEveryLuckyMoney() == 0 ? true : false);
                        btn_share.setText(tut.getEveryLuckyMoney() == 0 ? "去领取" : "已领取");
                        ivLuckmoney.setEnabled(tut.getEveryLuckyMoney() == 0 ? true : false);
                        ivLuckmoney.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                KumaHttp.getService().taskFinishTask(BaseConfig.Constant.TASK_LUCKYMONEY)
                                        .compose(RxCompos.<Long>getBEAllLoginCompos())
                                        .subscribe(new ProgressObserver<BaseEntity<Long>>(mContext) {
                                            @Override
                                            public void onNext(BaseEntity<Long> longBaseEntity) {
                                                showHongBao(longBaseEntity);
                                            }
                                        });
                            }
                        });
                        btn_share.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                KumaHttp.getService().taskFinishTask(BaseConfig.Constant.TASK_LUCKYMONEY)
                                        .compose(RxCompos.<Long>getBEAllLoginCompos())
                                        .subscribe(new ProgressObserver<BaseEntity<Long>>(mContext) {
                                            @Override
                                            public void onNext(BaseEntity<Long> longBaseEntity) {
                                                showHongBao(longBaseEntity);
                                            }
                                        });
                            }
                        });
                        if (tut.getEveryLuckyMoney() == 0) {
                            KumaHttp.getService().taskFinishTask(BaseConfig.Constant.TASK_LUCKYMONEY)
                                    .compose(RxCompos.<Long>getBEAllLoginCompos())
                                    .subscribe(new ProgressObserver<BaseEntity<Long>>(mContext) {
                                        @Override
                                        public void onNext(BaseEntity<Long> longBaseEntity) {
                                            showHongBao(longBaseEntity);
                                        }
                                    });
                        }
                    } else {
                        btn_share.setEnabled(true);
                        btn_share.setText("去领取");
                        btn_share.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                KumaToast.show(mContext, "必须要完成日常任务才可拆红包哦！");
                            }
                        });
                        ivLuckmoney.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                KumaToast.show(mContext, "必须要完成日常任务才可拆红包哦！");
                            }
                        });
                    }
                    tvLuckmoneyHint.setText(tut.getEveryLuckyMoney() == 0 ? "今日完成即可领取幸运红包" : "今日已领取幸运红包，再接再厉");
                    tvLuckmoneyHint.setTextColor(tut.getEveryLuckyMoney() == 0 ? getResources().getColor(R.color.mission_luckmoney_textcolor_normal) : getResources().getColor(R.color.mission_luckmoney_textcolor_alreadyget));
                    break;
                case 7:
                    setBtnEnable(btn_share, true);
                    btn_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MainActivity.openClearTask(mContext, MainActivity.MODE_NORMAL);
                        }
                    });
                    break;
            }
            if (btn_share.isEnabled()) {
                el.show();
            } else {
                el.hide();
            }
//            el.setOnStateChangeListener(new MyOnStateChangeListener(i));
        }
    }

    public static void open(Context context) {
        Intent i = new Intent(context, MissionActivity.class);
        context.startActivity(i);
    }

    @OnClick({R.id.btn_sign})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_sign:
                fetchSign();
                break;
        }
    }

//    class MyOnStateChangeListener implements ExpandableLayout.OnStateChangeListener {
//        private int index;
//
//        public MyOnStateChangeListener(int index) {
//            this.index = index;
//        }
//
//        @Override
//        public void onExpand(View v) {
//            ImageView iv_ex = elList.get(index).getHeaderRelativeLayout().findViewById(R.id.iv_ex);
//            iv_ex.setSelected(true);
//            for (int i = 0; i < elList.size(); i++) {
//                if (i == index) {
//                    continue;
//                }
//                elList.get(i).hide();
//            }
//        }
//
//        @Override
//        public void onCollapse(View v) {
//            ImageView iv_ex = elList.get(index).getHeaderRelativeLayout().findViewById(R.id.iv_ex);
//            iv_ex.setSelected(false);
//        }
//    }

    private void fetchSign() {
        KumaHttp.getService().taskSign()
                .compose(RxCompos.<Long>getBEAllLoginCompos())
                .map(new Function<BaseEntity<Long>, BaseEntity<Long>>() {
                    @Override
                    public BaseEntity<Long> apply(BaseEntity<Long> longBaseEntity) throws Exception {
//                        new SignDialog(mContext, longBaseEntity.getData()).show();
                        new CoinDialog(mContext, longBaseEntity.getData()).show();
                        return longBaseEntity;
                    }
                })
                .observeOn(Schedulers.io())
                .flatMap(new Function<BaseEntity, ObservableSource<BaseEntity<TaskUserTasks>>>() {
                    @Override
                    public ObservableSource<BaseEntity<TaskUserTasks>> apply(BaseEntity s) throws Exception {
                        return KumaHttp.getService().taskUserTasks();
                    }
                })
                .compose(RxCompos.<TaskUserTasks>getBELoginCompos())
                .subscribe(new ProgressObserver<TaskUserTasks>(mContext) {
                    @Override
                    public void onNext(TaskUserTasks taskUserTasks) {
                        handleData(taskUserTasks);
                    }

                    @Override
                    public void onErrorApi(BaseEntity be) {
                        super.onErrorApi(be);
                        if (BaseConfig.NetWork.CODE_ALREADYSIGN.equals(be.getCode())) {
                            btnSign.setEnabled(false);
                            btnSign.setText("明日签到获取金币");
                        }
                    }
                });

    }

    private void handleData(TaskUserTasks taskUserTasks) {
        if (taskUserTasks.getNoviceStatus() == 1) {
            llNew.setVisibility(View.GONE);
        } else {
            llNew.setVisibility(View.VISIBLE);
        }
        initMission(taskUserTasks);
        tvDay.setText(taskUserTasks.getSignTimes() + "天");
        switch (taskUserTasks.getSignTimes()) {
            default:
            case 7:
                ivDay7.setSelected(true);
            case 6:
                ivDay6.setSelected(true);
            case 5:
                ivDay5.setSelected(true);
            case 4:
                ivDay4.setSelected(true);
            case 3:
                ivDay3.setSelected(true);
            case 2:
                ivDay2.setSelected(true);
            case 1:
                ivDay1.setSelected(true);
            case 0:
                break;
        }
        btnSign.setEnabled(taskUserTasks.getSignStatus() == 0 ? true : false);
        if (taskUserTasks.getSignStatus() == 1) {
            btnSign.setText(taskUserTasks.getSignInfo());
        } else {
            btnSign.setText("");
        }
        if (taskUserTasks.getSignStatus() == 0) {
            fetchSign();
        }
    }

    @Subscriber(tag = BaseConfig.EventTag.ON_FINISHMISSION)
    private void onFinishMission(EventBean eb) {
        refreshHelper.loadMore();
    }

    private void setBtnEnable(Button btn, boolean isEnable) {
        btn.setEnabled(isEnable);
        btn.setText(isEnable ? "去完成" : "已完成");
    }

    private void showHongBao(BaseEntity<Long> longBaseEntity) {
        double number = Double.valueOf(longBaseEntity.getData());
        long coin = (long) number;
        NewHongBaoDialog dialog = new NewHongBaoDialog(mContext, coin);
        dialog.setOnClickGetMoneyListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GetMoneyCenterActivity.open(mContext);
            }
        });
        dialog.show();
        EventBus.getDefault().post(new EventBean("MissionActivity"), BaseConfig.EventTag.ON_FINISHMISSION);
    }
}
